package com.weichat.jwh.tool;


import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.net.ssl.HttpsURLConnection;

import org.apache.http.client.ClientProtocolException;
 
import org.json.JSONException;
import org.json.JSONObject;

import com.weichat.jwh.tool.MD5Util_jwh;
 

/*
'============================================================================
'api说明：
'createSHA1Sign创建签名SHA1
'getSha1()Sha1签名
'============================================================================
'*/
public class Signatrue_jwh {
	public static String getNonceStr() {
		Random random = new Random();
		return MD5Util_jwh.MD5Encode(String.valueOf(random.nextInt(10000)), "UTF-8");
	}
	public static String getTimeStamp() {
		return String.valueOf(System.currentTimeMillis() / 1000);
	}
	
   //创建签名SHA1
	public static String createSHA1Sign(SortedMap<String, String> signParams) throws Exception {
		StringBuffer sb = new StringBuffer();
		Set es = signParams.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			sb.append(k + "=" + v + "&");
			//要采用URLENCODER的原始值！
		}
		String params = sb.substring(0, sb.lastIndexOf("&"));
		return getSha1(params);
	}
	//Sha1签名
	public static String getSha1(String str) {
		if (str == null || str.length() == 0) {
			return null;
		}
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };

		try {
			MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
			mdTemp.update(str.getBytes("UTF-8"));
			byte[] md = mdTemp.digest();
			int j = md.length;
			char buf[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
				buf[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(buf);
		} catch (Exception e) {
			return null;
		}
	}
	
	public static String getjsApiTicket(String url,String assess_token) throws ClientProtocolException, IOException {
		String ticket="";
		URL url2=new URL(url+assess_token+"&type=jsapi");
		HttpsURLConnection con=(HttpsURLConnection) url2.openConnection();
		con.setRequestMethod("GET");
		con.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); 
		con.setDoOutput(true); 
		con.setDoInput(true);
		con.connect();
		InputStream input=con.getInputStream();
		byte[] c=new byte[input.available()];
		input.read(c);
		// String有一个构造方法，可以接受一个，字节的数组，来创建一个String.
		//这个过程，就实现了，字节数组转化为String的过程。
		String message=new String(c,"UTF-8");
		input.close();
		con.disconnect();
		
		JSONObject demoJson;
		try {
			demoJson = new JSONObject(message);
			System.out.println("=============="+demoJson.toString());

			ticket=demoJson.getString("ticket");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return ticket;
		
	}
	

	public static String appid=WeiChatConfig_jwh.appid;
	public static String secretid=WeiChatConfig_jwh.secretid;
 
	public static String ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=";
	public static void main(String[] args) throws Exception {
		
		
	/*	
		
		SortedMap<String, String> finalpackage = new TreeMap<String, String>();
		String timestamp = Signatrue.getTimeStamp();
		String nonce=Signatrue.getNonceStr();
		String token=TokenSaveRead.getToken();
		System.out.println("token-------"+token);
		//finalpackage.put("appId", WeiChatConfig.appid);
		finalpackage.put("timestamp", timestamp);
		finalpackage.put("noncestr",nonce );
		finalpackage.put("jsapi_ticket", getjsApiTicket(ticketUrl,token));
		finalpackage.put("url", "http://35fd28da.ngrok.io/weichat/jwh/weichatinit-jwh.html");
		//finalpackage.put("package", packages);
		//finalpackage.put("signType", WeiChatConfig.signType);
		String signature =Signatrue.createSHA1Sign(finalpackage);
		
		System.out.println("timestamp-----"+timestamp+"----nonce---"+nonce);
		
		
		System.out.println("signature=="+signature);*/
	}
}